package ks.server.authorization;

import ks.framework.interfaces.IAuthorization;
import ks.managers.user.User;
import ks.server.ServerContext;
import ks.server.persist.PersistentUserManager;

/**
 * Authentication manager bridges the gap on the server between the needs
 * of the Framework and the specific services to be provided by the 
 * UserManager.
 * 
 * @author George Heineman
 */
public class AuthorizationManager implements IAuthorization {

	/** Valid user can always pass. Scaffolding. */
	public static final String validUser = "VALIDUSER";
	
	/** Invalid user will always fail. Scaffolding. */
	public static final String invalidUser = "INVALIDUSER";
	
	/** Valid administrator can always pass. Scaffolding. */
	public static final String adminUser = "ADMIN";
	
	@Override
	public boolean authorize(String who, String encryptPass) {
		// SCAFFOLDING will eventually be removed
		if (who.equals (validUser)) { return true; }
		if (who.equals (invalidUser)) { return false; }

		PersistentUserManager uman = ServerContext.getUserManager();
		User u = uman.getUser(who);
		if (u == null) {
			return false;
		}
		
		return u.validate(encryptPass);
	}

	@Override
	public boolean authorizeAsAdmin(String who, String encryptPass) {
		// SCAFFOLDING will eventually be removed
		if (who.equals (adminUser)) { return true; }

		PersistentUserManager uman = ServerContext.getUserManager();
		User u = uman.getUser(who);
		if (u == null) {
			return false;
		}
		
		if (!u.validate(encryptPass)) { return false; }
		
		return u.isAdmin();
	}

	@Override
	public boolean selfRegister(String who, String pwd) {
		PersistentUserManager uman = ServerContext.getUserManager();
		User u = uman.getUser(who);
		if (u != null) {
			return false;
		}
		
		u = new User(who, pwd);
		return uman.addUser (u);
	}

}
